import { defineStore } from "pinia";
import { reactive, ref, shallowRef } from "vue";
import type { Music } from "../types/types";
import type { PersistenceOptions } from "pinia-plugin-persistedstate";
import Player from "@lrc-player/core";
import type { LyricsLine } from "@lrc-player/parse";

export const musicStore = defineStore('musicStore', () => {

    const audioElement = ref<HTMLAudioElement | null>(null);

    const player = shallowRef<Player | null>(null);     // 避免深度响应式转换

    // 存储当前音乐的播放信息
    const currentMusic = ref<
        {
            music_key: string;
            music_name: string;
            singer: string;
            music_url: string;
            duration: number;       // 播放总时长
            currentTime: number;        // 当前播放时间
            isPlaying: boolean;
            volume: number;     // 音量
            loopMode: 'off' | 'one' | 'all';    // 循环模式
            shuffleMode: boolean;
        }>({
            music_key: "",
            music_name: "",
            singer: "",
            music_url: "",          // 前四项属于基本信息
            duration: 0,
            currentTime: 0,
            isPlaying: false,
            volume: 100,
            loopMode: 'off',
            shuffleMode: false
        });

    // 更新当前音乐信息
    function setCurrentMusic(music: Partial<Music>) {
        currentMusic.value = {
            ...currentMusic.value,      // 保留现有的默认值
            ...music,   // 覆盖传递过来的属性
        }
    }

    // 存储歌词信息
    const lyricContent = ref<any | null>(null);

    const musicList = ref<Music[]>([]);

    function storageMusicInfoList(dataList: Music[]) {
        musicList.value.splice(0, musicList.value.length, ...dataList);
    }


    // 存储用户喜欢的音乐信息
    const likeMusicList = ref<Music[]>([]);
    // 更新用户喜欢的音乐列表
    function setLikeMusic(music: Music | Music[]) {
        const list = Array.isArray(music) ? music : [music];
        // likeMusicList.value.splice(0, likeMusicList.value.length, ...list);     // 使用splice会直接替换整个数组，改用push，直接末尾追加
        likeMusicList.value.push(...list);
    }

    // 存储历史播放记录的信息
    const storageMusicHistoryPlay = ref<Music[]>([]);
    // 添加记录
    function setHistoryInfo(music: Music) {
        // 不存储重复的音乐
        const history = storageMusicHistoryPlay.value.find((musicItem: Music) => {
            return musicItem.music_key === music.music_key;
        })
        if (!history) {
            storageMusicHistoryPlay.value.push(music);
        }
    }

    return {
        audioElement,
        // 音乐列表信息、存储音乐列表方法
        musicList, storageMusicInfoList,
        currentMusic, setCurrentMusic, lyricContent,
        likeMusicList, setLikeMusic,
        storageMusicHistoryPlay, setHistoryInfo
    }

}, {
    persist: {
        key: 'snow-music-list',
        paths: ['musicList', 'currentMusic', 'lyricContent', 'likeMusicList'],
        storage: localStorage
    } as PersistenceOptions
})